這一個章節跟第四天一樣主要是利用Javascript的Array物件中方法做資料處理。
some()
作為練習,是偵測在peoele
中是否有人大於19歲?const isAdult = people.some(person => ((new Date()).getFullYear()) - person.year >= 19);
console.log({isAdult});
every()
作為練習,是偵測在peoele
中全部的人都大於19歲?const allAdults = people.every(person => ((new Date()).getFullYear()) - person.year >= 19);
console.log({allAdults});
find()
作為練習,是尋找符合陣列中符合的資料。const comment = comments.find(comment => comment.id === 823423);
console.log(comment);
findIndex()
作為練習,是尋找符合陣列中符合資料的索引值。const index = comments.findIndex(comment => comment.id === 823423);
console.log(index);
true
。function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
true
,只要其中一樣不符合及回傳false
。function isBelowThreshold(currentValue) {
return currentValue < 40;
}
var array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
function isBigEnough(element) {
return element >= 15;
}
[12, 5, 8, 130, 44].find(isBigEnough); // 130
var array1 = [5, 12, 8, 130, 44];
function findFirstLargeNumber(element) {
return element > 13;
}
console.log(array1.findIndex(findFirstLargeNumber));
// expected output: 3
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
// add
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2, 0, 'drum');
// remove
var removed = myFish.splice(3, 1);
// remove and add
var removed = myFish.splice(2, 1, 'trumpet');
Array